/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @FraQiangGouba.java  2014年9月9日 下午3:56:34 - Guzhu
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.fragment;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaListFragment;
import com.android.tiango.baba.act.ActActiveDetail;
import com.android.tiango.baba.act.ActHome;
import com.android.tiango.baba.act.ActLogin;
import com.android.tiango.baba.act.ActSearch;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.BarModel;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.entity.SimpleProductModel;
import com.android.tiango.baba.entity.SimpleProductTopicEntity;
import com.android.tiango.baba.entity.SimpleProductTopicModel;
import com.android.tiango.baba.entity.SimpleTopicEntity;
import com.android.tiango.baba.entity.SimpleTopicModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.TimeToUtil;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.PullListView;
import com.android.tiango.baba.view.PullListView.PullListViewListener;
import com.android.tiango.baba.view.RoundImageView;
import com.nineoldandroids.util.StringUtil;

/**
 * 抢购吧
 * @author givon
 * 
 */
public class FraQiangGouba extends BaListFragment<SimpleProductTopicModel> implements
		com.android.tiango.baba.BaListFragment.AddHeaderViewCallBack, PullListViewListener,
		OnClickListener {
	private View headerView;
	private RoundImageView mLogo;
	private Button mQianDaoButton;
	private TextView mZding_1;
	private TextView mZding_2;
	private TextView mZding_3;
	private ImageView mIvZd_1;
	private ImageView mIvZd_2;
	private ImageView mIvZd_3;
	private TextView mTvQiandaoNum;
	private TextView mTvTatalNum;
	private Button mSearchButton;
	private RadioButton mRbQgRadioButton;
	private RadioButton mRbMyRadioButton;
	private BarModel mBarModel;
	private RelativeLayout mRe_1;
	private RelativeLayout mRe_2;
	private RelativeLayout mRe_3;
	private ArrayList<SimpleTopicModel> mSimpleTopicModels;
	private ArrayList<SimpleProductTopicModel> mSimpleProductTopicModels;
	private boolean isSign = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		setHeaderViewCallBack(this);
		// View view = super.onCreateView(inflater, container, savedInstanceState);
		View v = inflater.inflate(R.layout.layout_qianggouba, container, false);
		mRbQgRadioButton = (RadioButton) v.findViewById(R.id.rb_qianggouba);
		mRbMyRadioButton = (RadioButton) v.findViewById(R.id.rb_myba);
		mRbMyRadioButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ActHome.WEI_BA_TYPE == ActHome.QIANG_GOU_BA) {
					((ActHome) getActivity()).switchFragment(ActHome.MY_BA);
				}
			}
		});
		RadioGroup mRadioGroup = (RadioGroup) v.findViewById(R.id.rg_T);
		mAdapter = new ListAdapter(getActivity());
		mListView = (PullListView) v.findViewById(R.id.id_pull_listview);
		mListView.setHeaderDividersEnabled(false);
		mListView.setFooterDividersEnabled(false);
		mListView.setSelector(android.R.color.transparent);
		if (null != addHeaderViewCallBack) {
			addHeaderViewCallBack.addHeaderView();
		}
		mSearchButton = (Button) v.findViewById(R.id.bt_serach);
		mSearchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showActivity(ActSearch.class);
			}
		});
		mImageLoader = new ImageLoader(getActivity(), R.drawable.ic_launcher);
		mListView.setAdapter(mAdapter);
		mListView.setPullListener(this);
		mListView.startOnRefresh();
		loadWeibaDetail();
		loadSpecialtopics();
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void addHeaderView() {
		headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_fragment_qianggou,
				null);
		mLogo = (RoundImageView) headerView.findViewById(R.id.iv_logo);
		mQianDaoButton = (Button) headerView.findViewById(R.id.bt_qd);
		mQianDaoButton.setOnClickListener(this);
		mTvTatalNum = (TextView) headerView.findViewById(R.id.tv_tz_num);
		mTvQiandaoNum = (TextView) headerView.findViewById(R.id.tv_qiandao_num);
		mZding_1 = (TextView) headerView.findViewById(R.id.tv_zd_1);
		mZding_2 = (TextView) headerView.findViewById(R.id.tv_zd_2);
		mZding_3 = (TextView) headerView.findViewById(R.id.tv_zd_3);
		// mIvZd_1 = (ImageView) headerView.findViewById(R.id.image_1);
		// mIvZd_2 = (ImageView) headerView.findViewById(R.id.image_2);
		// mIvZd_3 = (ImageView) headerView.findViewById(R.id.image_3);
		mRe_1 = (RelativeLayout) headerView.findViewById(R.id.re_1);
		mRe_2 = (RelativeLayout) headerView.findViewById(R.id.re_2);
		mRe_3 = (RelativeLayout) headerView.findViewById(R.id.re_3);
		mRe_1.setVisibility(View.GONE);
		mRe_2.setVisibility(View.GONE);
		mRe_3.setVisibility(View.GONE);
		mListView.addHeaderView(headerView);

	}

	@Override
	public void onStart() {
		super.onStart();
		mRbQgRadioButton.setChecked(true);
	}

	@Override
	protected View getItemView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		final SimpleProductTopicModel model = mAdapter.getItem(position);
		if (null == convertView) {
			convertView = LayoutInflater.from(getActivity())
					.inflate(R.layout.item_qianggouba, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}
		holder = (ViewHolder) convertView.getTag();
		if (null != model) {
			SimpleProductModel product = model.getSimpleProduct();
			if (null != product) {
				holder.tv_title.setText(product.getProductName());
				holder.tv_actcomments.setText(model.getReplyNumber() + "");
				holder.tv_acttoview.setText(model.getReadNumber() + "");
				holder.tv_date.setText(TimeToUtil.getSystemTimeSetFormat(model.getStartTime(),
						TimeToUtil.ACCURATE_TO_THE_DAY));
				mImageLoader.loadImage(product.getMerchantLogo(), holder.iv_brandimg);
				// if(!StringUtils.isEmpty(product.getMerchant())){
				// holder.tv_brand.setText(product.getMerchant());
				// }
			}
		}
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != model) {
					Intent intent = new Intent(getActivity(), ActActiveDetail.class);
					intent.putExtra("BarId", model.getBarId());
					intent.putExtra("TopicId", model.getTopicId());
					startActivity(intent);
				}
			}
		});
		return convertView;
	}

	private class ViewHolder {
		TextView tv_title;
		TextView tv_date;
		TextView tv_actcomments;
		TextView tv_acttoview;
		ImageView iv_brandimg;
		TextView tv_brand;

		public ViewHolder(View v) {
			tv_actcomments = (TextView) v.findViewById(R.id.tv_actcomments);
			tv_acttoview = (TextView) v.findViewById(R.id.tv_acttoview);
			// tv_brand = (TextView) v.findViewById(R.id.tv_brand);
			tv_title = (TextView) v.findViewById(R.id.tv_title);
			iv_brandimg = (ImageView) v.findViewById(R.id.iv_brandimg);
			tv_date = (TextView) v.findViewById(R.id.tv_date);
		}
	}

	@Override
	public void onPullRefresh() {
		mPageIndex = 1;
		loadData();
	}

	@Override
	public void onPullLoadMore() {
		if (mPageIndex < 1) {
			mPageIndex = 1;
		}
		mPageIndex += 1;
		loadData();

	}

	private void initViewData() {
		if (null != mBarModel) {
			mTvQiandaoNum.setText(mBarModel.getTodaySignNumber() + "");
			mTvTatalNum.setText(mBarModel.getTodayTopicNumber() + "");
			mImageLoader.loadImage(mBarModel.getBarIcon(), mLogo);
			isSign = StringUtils.getDefaultBoolean(mBarModel.getIsSigned());
			if (isSign) {
				mQianDaoButton.setText("已签到");
			} else {
				mQianDaoButton.setText("签到");
			}
		}
	}

	/**
	 * 获取抢购吧详情
	 */
	private void loadWeibaDetail() {
		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		params.put("barId", "0");
		params.put("token", ShareCookie.getToken());
		params.put("signature", "");
		clientAsync.get(HttpUrl.getUrl(HttpUrl.PRODUCTBAR), params, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				mBarModel = (BarModel) arg0;
				initViewData();

			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				if (StringUtil.isEmpty(arg1)) {
					arg1 = getStringValue(R.string.info_net_error);
				}
				ToastUtils.showMessage(arg1);
			}
		}, BarModel.class, true);

	}

	/**
	 * 置顶帖列表
	 */
	private void loadSpecialtopics() {
		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		clientAsync.setPrintLog(true);
		HttpParams params = new HttpParams();
		params.put("barId", "0");
		params.put("signature", "");
		clientAsync.get(HttpUrl.getUrl(HttpUrl.SPECIALTOPICS), params, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				SimpleTopicEntity mSimpleTopicEntity = (SimpleTopicEntity) arg0;
				if (null != mSimpleTopicEntity && mSimpleTopicEntity.getData() != null) {
					mSimpleTopicModels = mSimpleTopicEntity.getData();
					initZdView();
				}

			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				if (StringUtil.isEmpty(arg1)) {
					arg1 = getStringValue(R.string.info_net_error);
				}
				ToastUtils.showMessage(arg1);
			}
		}, SimpleTopicEntity.class);

	}

	/**
	 * 抢购吧活动列表
	 */
	private void loadProducttopics() {
		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		params.put("barId", "0");
		params.put("pageIndex", mPageIndex);
		params.put("pageSize", Constants.PAGE_SIZE);
		params.put("signature", "");
		clientAsync.post(HttpUrl.getUrl(HttpUrl.PRODUCTTOPICS), params, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				SimpleProductTopicEntity entity = (SimpleProductTopicEntity) arg0;
				if (null != entity && entity.getData() != null) {
					mSimpleProductTopicModels = entity.getData();
					mAdapter.putData(mSimpleProductTopicModels);
				}
				mListView.onRefreshFinish();
				mListView.onLoadFinish();
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				mPageIndex -= 1;
				mListView.onRefreshFinish();
				mListView.onLoadFinish();
				if (StringUtil.isEmpty(arg1)) {
					arg1 = getStringValue(R.string.info_net_error);
				}
				ToastUtils.showMessage(arg1);
			}
		}, SimpleProductTopicEntity.class);
	}

	/**
	 * 签到
	 */
	private void loadSign() {
		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		params.put("barId", "0");
		params.put("token", ShareCookie.getToken());
		params.put("signature", "");
		clientAsync.post(HttpUrl.getUrl(HttpUrl.SIGNIN), params, new HttpCallBack() {
			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				BaseEntity entity = null;
				try {
					entity = JSONObject.parseObject((String) arg0, BaseEntity.class);
				} catch (Exception e) {
				}
				if (null != entity) {
					if (entity.getState() == 1) {
						// if (!StringUtils.isEmpty(entity.getMessage())) {
						// ToastUtils.showMessage(entity.getMessage());
						// } else {
						ToastUtils.showMessage(getStringValue(R.string.info_sign_ok));
						// }
						mBarModel.setTodaySignNumber(mBarModel.getTodaySignNumber() + 1);
						mBarModel.setIsSigned(1);
						initViewData();
					} else {
						isSign = false;
						ToastUtils.showMessage(getStringValue(R.string.info_net_error));

					}
				}

			}

			@Override
			public void onHttpStarted() {
				showWaitingDialog();
			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (StringUtil.isEmpty(arg1)) {
					arg1 = getStringValue(R.string.info_net_error);
				}
				ToastUtils.showMessage(arg1);
			}
		});
	}

	/**
	 * 初始化置顶View
	 */

	private void initZdView() {
		if (null != mSimpleTopicModels) {
			for (int i = 0; i < mSimpleTopicModels.size(); i++) {
				SimpleTopicModel model = mSimpleTopicModels.get(i);
				if (null == model) {
					break;
				}
				switch (i) {
				case 0:
					mZding_1.setText(model.getTopicName());
					mRe_1.setVisibility(View.VISIBLE);
					break;
				case 1:
					mZding_2.setText(model.getTopicName());
					mRe_2.setVisibility(View.VISIBLE);
					break;
				case 2:
					mZding_3.setText(model.getTopicName());
					mRe_3.setVisibility(View.VISIBLE);
					break;

				default:
					break;
				}
			}
		}
	}

	private void loadData() {
		loadProducttopics();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_qd:
			// TODO 签到 需要先判断登录再判断签到没有
			if (ShareCookie.isLoginAuth()) {
				if (!isSign) {
					loadSign();
				} else {
					ToastUtils.showMessage(getStringValue(R.string.info_resign_ok));
				}
			} else {
				showActivity(ActLogin.class);
			}
			break;

		default:
			break;
		}
	}

}
